package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"order/global"
	"order/models/mysql"
	"order/pkg"
	"strconv"
	"time"
)

type LoginController struct {
	beego.Controller
}

// 用户密码登录
func (l *LoginController) UserLogin() {
	mobile := l.GetString("mobile")
	password := l.GetString("password")
	//参数校验
	if mobile == "" || password == "" {
		l.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "参数不能为空",
			Data: nil,
		}
		l.ServeJSON()
		return
	}
	//数据库查询用户
	u, db := mysql.GetUserByMobile(mobile, password)
	if db.RowsAffected != 1 || db.Error != nil {
		l.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "查询用户失败",
			Data: nil,
		}
		l.ServeJSON()
		return
	}
	//将ID存入token
	token, err := pkg.SetJwtToken(time.Now().Unix(), strconv.Itoa(int(u.ID)))
	if err != nil {
		l.Data["json"] = global.JsonR{
			Code: -1,
			Msg:  "token生成失败",
			Data: nil,
		}
		l.ServeJSON()
		return
	}
	l.Data["json"] = global.JsonR{
		Code: 0,
		Msg:  "登录成功",
		Data: token,
	}
	l.ServeJSON()
	return
}
